package mypack.openworld;

import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class ServerInteraction extends AsyncTask<String, Double, String> {

    ServerResponseProcessor serverResponseProcessor;

    ServerInteraction(ServerResponseProcessor serverResponseProcessor) {
        super();
        this.serverResponseProcessor = serverResponseProcessor;
    }

    @Override
    protected void onPostExecute (String result) {
        serverResponseProcessor.process(result);
    }

    @Override
    protected String doInBackground(String... params) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://openworld.herzen.spb.ru" + params[0]);
        ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        list.add(new BasicNameValuePair("data", params[1]));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            String string;
            while ((string = bufferedReader.readLine()) != null) {
                stringBuilder.append(string + "\n");
            }
            return stringBuilder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
